@page
@inject IConfiguration Config;

<!DOCTYPE html>
<html>
    <body>
        <h1>Access cookie using AJAX call to API from different domain</h1>
        <button id="test">Test CORS</button><br/><br/>
        <button id="fetchName">Fetch</button>
        <script>
            async function getCookie(){
                const response = await fetch("@Config["endpoint"]/message-cookie", {
                    method: "GET",
                    credentials: 'include'
                });

                if (response.ok){
                        const messageCookie = document.cookie
                                        .split("; ")
                                        .find(row => row.startsWith("message="))
                                        .split("=")[1];

                        return messageCookie;
                }
                else {
                    return null;
                }
            }

            async function getName(){
                var message = await getCookie();
                alert(message);
            }

            async function testCors(){
                const response = await fetch("@Config["endpoint"]/test-cors", {
                    method : "GET",
                    headers : { 
                    "Content-Type": "application/json"
                    }
                });
                
                const result = await response.json();
                alert(result.message);
            }

            const btn = document.getElementById("fetchName");
            btn.addEventListener("click", async () => {
                await getName();
            });

            const btn2 = document.getElementById("test");
            btn2.addEventListener("click", async () => {
                await testCors();
            });

        </script>
    </body>
</html>